package handler

import (
	"context"
	"good-server/basic/global"
	"good-server/internal/dao"
	"good-server/internal/model"
	"good-server/pkg"
	__ "good-server/proto"
)

type GoodServer struct {
	__.UnimplementedGoodServerServer
}

// SayHello implements helloworld.GreeterServer
func (s *GoodServer) CreateGood(_ context.Context, in *__.CreateGoodReq) (*__.CreateGoodResp, error) {
	good := model.Good{
		Picture:     in.Picture,
		Name:        in.Name,
		GoodNum:     in.GoodNum,
		GoodClassId: uint(in.GoodClassId),
		Incule:      in.Inclue,
		Number:      int32(in.Number),
		Price:       float64(in.Price),
	}

	dao.Create(&good)

	pkg.ElasticSearch(good)

	return &__.CreateGoodResp{
		Message: "发布成功",
		Code:    200,
	}, nil

}

func (s *GoodServer) CreateAttribute(_ context.Context, in *__.CreateAttributeReq) (*__.CreateAttributeResp, error) {

	dao.Create(&model.GoodAttribute{
		GoodId: in.GoodId,
		Name:   in.Name,
	})

	return &__.CreateAttributeResp{
		Message: "发布成功",
		Code:    200,
	}, nil

}

func (s *GoodServer) CreateValue(_ context.Context, in *__.CreateValueReq) (*__.CreateValueResp, error) {

	dao.Create(&model.GoodAttrubuteValue{
		AttributeId: uint(in.AttributeId),
		Name:        in.Name,
	})

	return &__.CreateValueResp{
		Message: "发布成功",
		Code:    200,
	}, nil

}

func (s *GoodServer) ListGood(_ context.Context, in *__.ListGoodReq) (*__.ListGoodResp, error) {

	var good []*model.Good
	var lists []*__.ListGood

	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	global.DB.Offset(int(offset)).Limit(int(pageSize)).Find(&good)

	for _, v := range good {

		lists = append(lists, &__.ListGood{
			Name:        v.Name,
			Picture:     v.Picture,
			GoodNum:     v.GoodNum,
			GoodClassId: int64(v.GoodClassId),
			Inclue:      v.Incule,
			Number:      int64(v.Number),
			Price:       float32(v.Price),
			Id:          int64(v.Id),
		})

	}

	return &__.ListGoodResp{
		List: lists,
	}, nil

}
